package com.tan00xu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.tan00xu.dao.ArticleMapper;
import com.tan00xu.dao.CategoryMapper;
import com.tan00xu.pojo.Article;
import com.tan00xu.pojo.Category;
import com.tan00xu.service.CategoryService;
import com.tan00xu.vo.CategoryVo;
import com.tan00xu.vo.Result;
import org.junit.jupiter.api.Test;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
public class CategoryServiceImpl implements CategoryService {

    @Autowired
//    @Resource
    private CategoryMapper categoryMapper;

    @Autowired
    private ArticleMapper articleMapper;

    /**
     * 根据分类id获取分类的详细信息
     * @param categoryId 分类id
     * @return CategoryVo
     */
    @Override
    public CategoryVo getCategoryById(Long categoryId) {
        Category category = categoryMapper.selectById(categoryId);
//        CategoryVo categoryVo = new CategoryVo();
//        BeanUtils.copyProperties(category, categoryVo);
        return copy(category);
    }

    /**
     * 获取文章的所有分类
     *
     * @return Result 分类数据
     */
    @Override
    public Result listAllCategories() {
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.select(Category::getId, Category::getCategoryName);
        List<Category> categories = categoryMapper.selectList(queryWrapper);
        List<CategoryVo> categoryVo = copyList(categories);
        return Result.success("获取文章的所有分类成功",categoryVo);
    }

    /**
     * 获取文章的所有分类的详细信息
     *
     * @return
     */
    @Override
    public Result listAllCategoriesDetail() {
        List<Category> categories = categoryMapper.selectList(null);
        return Result.success("获取文章的所有分类的详细信息成功", copyList(categories));
    }

    /**
     * 根据分类id统计该分类下的文章数
     * @param categoryId 分类id
     * @return Long 文章数
     */
    @Override
    public Long countArticleByCategoryId(Long categoryId) {
        LambdaQueryWrapper<Article> countWrapper = new LambdaQueryWrapper<>();
        countWrapper.eq(Article::getCategoryId, categoryId);
        return this.articleMapper.selectCount(countWrapper);
    }


    public CategoryVo copy(Category category) {
        CategoryVo categoryVo = new CategoryVo();
        BeanUtils.copyProperties(category, categoryVo);
        Long countArticle = countArticleByCategoryId(category.getId());
        categoryVo.setCountArticle(countArticle);
        return categoryVo;
    }

    public List<CategoryVo> copyList(List<Category> categoryList) {
        List<CategoryVo> categoryVoList = new ArrayList<>();
        for (Category category : categoryList) {
            categoryVoList.add(copy(category));
        }
        return categoryVoList;
    }

}
